package com.blog.config;

import com.blog.service.SysUpdateDatabase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.text.ParseException;

/**
 * @author cgx
 * @Date 2022/1/19 16:38
 * 系统启动停止监听器
 */
@Slf4j
@Component
public class StartupContextListener implements ServletContextListener {


    @Resource
    private SysUpdateDatabase sysUpdateDatabase;

    /**
     * 系统启动初始化
     * @param
     * @return
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {

        log.info("系统开始初始化");
        ServletContext servletContext = event.getServletContext();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        SpringContextHolder.setApplicationContext(context);
        //自动更新sql，用于执行新添加的sql
        autoUpdateSql();
    }



    /**
     * 自动升级数据库
     */
    private void autoUpdateSql(){
        try {
            sysUpdateDatabase.updateDatabase();
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("=====>系统停止");
    }
}
